package com.leonzhangxf;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.leonzhangxf.configuration.DataSourceConfiguration;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

/**
 * @author leonzhangxf
 */
public class DbConfigChanger {

    public static void main(String[] args) throws Exception {
        // 初始化配置
        CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("127.0.0.1:2181")
            .retryPolicy(new ExponentialBackoffRetry(1000, 3, 10000))
            .namespace("program_3").build();

        client.start();

        updateConfig(client);
        getConfig(client);
    }

    static final String datasourcePath = "/datasource";
    static ObjectMapper objectMapper = new ObjectMapper();

    static void getConfig(CuratorFramework client) throws Exception {
        byte[] bytes = client.getData()
            .forPath(datasourcePath);
        System.out.println(objectMapper.readValue(bytes, DataSourceConfiguration.JdbcProperties.class));
    }

    static void updateConfig(CuratorFramework client) throws Exception {
        DataSourceConfiguration.JdbcProperties config = new DataSourceConfiguration.JdbcProperties();
        config.setUrl("jdbc:mysql://localhost:3306/test1?serverTimezone=Asia/Shanghai&useSsl=false");
        // config.setUrl("jdbc:mysql://localhost:3306/test2?serverTimezone=Asia/Shanghai&useSsl=false");
        config.setDriver("com.mysql.cj.jdbc.Driver");
        config.setUsername("root");
        config.setPassword("root");

        client.blockUntilConnected();
        Stat stat = client.checkExists().forPath(datasourcePath);
        System.out.println("exist?: " + (null != stat));
        if (null == stat) {
            System.out.println("create node");
            client.create().creatingParentsIfNeeded()
                .forPath(datasourcePath);
        }

        client.setData()
            .forPath(datasourcePath, objectMapper.writeValueAsBytes(config));
    }
}
